<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model\LazyCommon;

use App\Base\BaseModel;
use App\Entity\User;
use App\Setting\LazyCommon\UserSetting;
use App\Model\LazyCommon\UserGroupsModel;

class UserModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须】
     */
    public function listSettingDefault()
    {
        $settings = new UserSetting($this->getDoctrine());
        return $settings->listConfig();
    }
    /*
      * 通用Rep
      */
    public function getRep()
    {
        $settings = new UserSetting($this->getDoctrine());
        return $this->em->getRepository($settings->bundleName.":".$settings->entityName);

    }

    /**
     * @param string $account
     * @return int
     */
    public function checkAccount4Reg($account)
    {//检查账号是否被占用
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("User")->where("account = :account")->setParameter("account",$account);
        return $qb->execute()->rowCount();
    }

    /**
     * @param $account
     * @param $password
     * @return null|User
     */
    public function checkAccountPassword($account, $password)
    {//检查账号密码
        $user = $this->getRep()->findOneBy(array(
            "account"       => $account,
            "password"      => $password,
            "ban"           => 0
        ));
        return $user;
    }

    /**
     * @param $frontData
     * @param $groups
     * @return User
     */
    public function commReg($frontData,$groups = 1)
    {//普通注册，需账号、密码、安全密码和用户组
        //注册所需基本字段及默认值
        $defaultInsertData = array(
            "account"   => "",
            "password"  => "",
            "passwordPay"  => "",
            "groups"  => $groups,
            "addTime"  => time(),
            "headPic"  => "/public/default_user.png",
            "level"  => 0,
            "parent"  => 0,
            "lastLoginTime"  => 0,
            "lastLoginIp"  => "",
//            "roles" => json_encode($this->getUserRolesByGroups($groups))
        );
        $user = new User();
        foreach ($defaultInsertData as $key => $val) {
            $func = "set".ucfirst($key);
            if (isset($frontData[$key])) {
                $user->$func($frontData[$key]);
            } else {
                $user->$func($val);
            }
        }
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        return $user;
    }

    /**
     * @param $account
     * @param $password
     * @param $request
     * @return null|User
     */
    public function commLogin($account,$password,$request)
    {

        $userLoginLogModel = new UserLoginLogModel($this->getDoctrine());
        $loginInfo = $userLoginLogModel->createLoginLogInfo($request);
        if ($user = $this->checkAccountPassword($account,$password))
        {//账号密码匹配成功
            $loginInfo["passwordError"] = 0;
            $this->updateUserInfo($user->getId(),array(
                "lastLoginTime" =>time(),
                "lastLoginIp"   =>$loginInfo["loginIp"],
            ));
        }
        else
        {//账号密码错误
            $loginInfo["passwordError"] = 1;
        }
        $userLoginLogModel->addLoginLog($loginInfo);
        return $user;
    }

    /**
     * @param $user User
     * @return mixed
     */
    public function createSessionData($user)
    {
        //设置用session
        $sessionData["id"] = $user->getId();
        $sessionData["phone"] = $user->getPhone();
        $sessionData["role"] = $user->getRoles();
        $sessionData["openid"] = $user->getOpenid();
        $sessionData["groups"] = $user->getGroups();
        return $sessionData;
    }

    /**
     * @param $phone
     * @return null|User
     */
    public function getByPhone($phone)
    {
        //todo 这里账号就是手机，后期看看是否需要区分开来，反正字段是有的
        $user = $this->getRep()->findOneBy(array("phone"=>$phone));
        return $user;
    }

    /**
     * @param $openId
     * @return null|User
     */
    public function getByWeChetId($openId)
    {
        $user = $this->getRep()->findOneBy(array("openid"=>$openId));
        if (!$user) {
            $user = new User();
            $user->setGroups(3)
                ->setAccount("U".date(YMDHIS))
                ->setPassword("4297f44b13955235245b2497399d7a93")
                ->setPasswordPay("4297f44b13955235245b2497399d7a93")
                ->setOpenid($openId)
                ->setAddTime(time());
            $this->em->persist($user);
            $this->em->flush();
        }
        return $user;
    }

    /**
     * @param $userId
     * @return array
     */
    public function getUserRolesByUser($userId)
    {//获取用户角色
        $user = $this->getUserById($userId);

        if ($user && $user->getGroups()) {
            $userGroups = $user->getGroups();
            $Roles = $this->getUserRolesByGroups($userGroups);
            return $Roles;
        } else {
            return array();
        }
    }

    /**
     * @param $userGroups
     * @return array
     */
    public function getUserRolesByGroups($userGroups)
    {//获取分组角色
        $qb = $this->getQueryBuilder();
        $qb->select("Role.code")
            ->from("User_Groups_Role","User_Groups_Role")
            ->where("User_Groups_Role.groups = :groups")->setParameter("groups",$userGroups)
            ->leftJoin("User_Groups_Role","Role","Role","User_Groups_Role.role = Role.id")
        ;
        $UserGroupsRole =  $qb->execute()->fetchAll();
        $Roles = array();
        foreach ($UserGroupsRole as $row) {
            $Roles[] = $row["code"];
        }
        return $Roles;
    }

    /**
     * @param $userId
     * @return null|User
     */
    public function getUserById($userId)
    {//获取用户信息
        return $this->getRep()->find($userId);
    }

    /**
     * @param int $userId
     * @param array $userInfo
     */
    public function updateUserInfo($userId,$userInfo)
    {//更新个人信息
        $qb = $this->getQueryBuilder();
        $qb->update("User");
        foreach ($userInfo as $key => $val) {
            $qb->set($key,":$key")->setParameter("$key",$val);
        }
        $qb->where("id = :id")->setParameter("id",$userId);
        $qb->execute();
    }


    public function getUserFromIds($ids)
    {
        $qb = $this->em->createQueryBuilder();
        $qb->from("App:User","User")
            ->select("User.id,User.nickName,User.openid")
            ->where(
                $qb->expr()->in("User.id",$ids)
            );
        return $qb->getQuery()->getResult();
    }

    public function getBaseInfo(User $user)
    {
        $UserGroupsModel = new UserGroupsModel($this->getDoctrine());
        if ($user) {
            return array(
                "id"            => $user->getId(),
                "account"       => $user->getAccount(),
                "headPic"       => $user->getHeadPic(),
                "grade"         => $user->getQq(),//年级ID
                "nickName"      => $user->getNickName(),
                "lastLoginIp"   => $user->getLastLoginIp(),
                "openid"        => $user->getOpenid(),
                "phone"         => $user->getPhone(),
                "addTime"       => date("Y-m-d H:i",$user->getAddTime()),
                "level"         => $user->getGroups() - 3,
                "groups"        => $UserGroupsModel->getGroupNameByGroup($user->getGroups())
            );
        }
        return array();
    }


    public function getUsersByGroups($groups)
    {//获取用户信息
        $rst =  $this->getRep()->findBy(array(
            "groups"=>$groups,
        ),array("id"=>"DESC"));
        $data = [];
        foreach ($rst as $user) {
            $data[$user->getId()] = $user->getRealName();
        }
        return $data;
    }


}